use strict;
use utf8;

use LWP::UserAgent;
use Encode;
use HTML::TokeParser;
use XML::RSS;
use DateTime;
use DateTime::Format::Strptime;

my $ua = LWP::UserAgent->new();
$ua->default_headers->push_header('Referer' => 'http://comic.zpoo.com/index.html');

my $response = $ua->get('http://bbs.zpoo.com/api/javascript.php?function=threads&fids=14_192_19_20_21_22_23_2106_3063_1209_1210&maxlength=50&startrow=0&picpre=http%3A%2F%2Fwww.zpoo.com%2Fpic%2Fdot.gif&items=20&digest=0&newwindow=1&highlight=1&forum=0&author=0&dateline=1&orderby=dateline&verify=cc1ec285069fa3ec0ca6f6aa98bc0050');
my @itemlist;

if($response -> is_success) 
{
    my $in_content = Encode::decode("gb2312", $response->content);
    $in_content=~ s/document.writeln\("//g;
    $in_content=~ s/"\);//g;

    my $stream = HTML::TokeParser->new(\$in_content) or die $!;
    my $tag;
    my $dparser = new DateTime::Format::Strptime(pattern=>'%Y-%m-%d %H%M');

    while($tag = $stream->get_tag('img'))
    {
        my $dt = $dparser->parse_datetime($stream->get_trimmed_text('a'));
        $tag = $stream->get_tag('a');
        if( $tag->[1]{title}=~/\x{66f4}\x{65b0}/ )
        {   
            $itemlist[$#itemlist+1]={title=>$tag->[1]{title}, url=>$tag->[1]{href}, dt=>$dt};
        }
    }
}
else {die $response->status_line;}

my $rss = XML::RSS->new (version => '1.0' );

$rss->channel(
    title => "Zpoo update monitor", link => "http://comic.zpoo.com", description => "online comic updates",
    dc => { date => DateTime->now, subject => 'japanese comics sharing', creator => 'chunju+zpoo@gmail.com', publisher => 'zpoocn@gmail.com', language => 'zh-cn'});

foreach (@itemlist)
{
    $rss->add_item( title => $_->{title}, link => $_->{url}, dc => {date => $_->{dt} });
}

$rss->save("zpoo.rss") or die$!;
my $now = DateTime->now;
print "zpoo.rss created -$now\n";

